import { ref , getCurrentInstance } from "vue";
import { loginApi } from '@/controller/UserApi'
import { message } from "ant-design-vue";
import { useLoginStore } from "@/stores/loginStore"
import { storeToRefs } from "pinia";
import { useRouter } from "vue-router";
import { emitter } from "@/utils/Mitt";

interface Login {
    account : string,
    password : string
}

export default function () {

    const loginStore = useLoginStore();


    let { proxy } = getCurrentInstance() as any;

    const router = useRouter();

    const { loginInfo } = storeToRefs(loginStore);

    let login = ref<Login>({
        account : '',
        password : ''
    })

    let remember = ref(false);


    let loginForm = ref();
    let loginIng = ref(false);
    function submit() {
        loginForm.value
            .validate()
            .then(() => {
                loginIng.value = true;
                loginApi(login.value).then( res => {
                    if(res.code == 200) {
                        loginInfo.value = res.data;
                        router.push('/index/home');
                        loginIng.value = false;
                        emitter.emit('connectWs');
                    }else {
                        message.error(res.msg);
                        loginIng.value = false;
                    }
                });
            })
            .catch( (error : any) => {
                console.log('error', error);
                loginIng.value = false;
            });
    }


    return {
        login , remember , submit , loginForm , loginIng
    }
}
